import time
import tkinter as tk
import keyboard  # 需要安装 keyboard 库
import os
import json
import pyfrp


class App:
    default_config = {
        "hot_key": "Ctrl+H",
        "mail_addr": "",
        "auto_connect": False
    }

    def __init__(self, root):
        self.root = root
        self.root.title("远程工具")
        self.root.resizable(False, False)  # 禁止调整窗口大小
        if not os.path.exists("temp"):
            os.mkdir("temp")
        self.CONFIG_FILE = "temp/c.bat"
        self.config = self.read_config()
        self.frpc = pyfrp.Frpc()

        # 输入框
        self.email_label = tk.Label(root, text="请输入邮箱地址:")
        self.email_label.pack(pady=10)

        self.email_entry = tk.Entry(root, width=30)
        self.email_entry.insert(0, self.config.get("mail_addr", ""))
        self.email_entry.pack(pady=1, padx=10)
        self.email_entry.bind("<KeyRelease>", self.on_email_entry_change)

        # 输出窗口
        self.output_label = tk.Label(root, text="IP: 192.168.1.1\n端口: 8000", font=("Arial", 14))
        self.output_label.pack(pady=20)

        # 自动连接选项
        self.auto_connect_var = tk.BooleanVar(value=self.config.get("auto_connect", False))
        self.auto_connect_check = tk.Checkbutton(
            root, text="自动连接", variable=self.auto_connect_var, command=self.on_auto_connect_toggle
        )
        self.auto_connect_check.pack(pady=5)
        if self.config.get("auto_connect", False):
            self.start_frpc()

        # 热键设置
        self.hotkey_label = tk.Label(root, text="设置热键:")
        self.hotkey_label.pack(pady=5)

        self.custom_hotkey_entry = tk.Entry(root, width=30)
        self.custom_hotkey_entry.insert(0, self.config.get("hot_key", "Ctrl+H"))
        self.custom_hotkey_entry.pack(pady=5)
        self.custom_hotkey_entry.bind("<KeyRelease>", self.on_hotkey_entry_change)

        self.set_hotkey_button = tk.Button(root, text="设置", command=self.update_hotkey)
        self.set_hotkey_button.pack(pady=5)

        # 隐藏窗口的定时器
        self.hide_timer = self.root.after(60000, self.hide_window)  # 60秒后隐藏窗口

        # 注册热键
        self.current_hotkey = self.config.get("hot_key", "Ctrl+H")
        self.register_hotkey()

    def start_frpc(self):
        self.frpc.set_mail(self.config["mail_addr"])
        self.frpc.run()
        for i in range(5):
            if self.frpc.is_active:
                self.update_output_label(self.frpc.server_addr, self.frpc.remote_port)
                break
            time.sleep(1)
        else:
            self.update_output_label("链接错误", "")

    def read_config(self):
        """读取配置文件"""
        if not os.path.exists(self.CONFIG_FILE):
            print(f"{self.CONFIG_FILE} 不存在，返回默认配置并写入文件.")
            config = self.default_config
            self.write_config(config)
            return config

        with open(self.CONFIG_FILE, 'r') as file:
            try:
                config = json.load(file)
                return config
            except json.JSONDecodeError:
                print("配置文件格式错误，返回默认配置.")
                config = self.default_config
                self.write_config(config)
                return config

    def write_config(self, config):
        """写入配置文件"""
        with open(self.CONFIG_FILE, 'w') as file:
            json.dump(config, file, indent=4)
        print(f"{self.CONFIG_FILE} 已保存配置.")

    def on_hotkey_entry_change(self, event):
        """当热键输入框内容发生变化时"""
        if self.hide_timer:
            self.root.after_cancel(self.hide_timer)

    def on_email_entry_change(self, event):
        """当 email_entry 的内容发生变化时触发"""
        current_text = self.email_entry.get()
        print(f"输入框内容已修改: {current_text}")

        # 重置定时器
        if self.hide_timer:
            self.root.after_cancel(self.hide_timer)

        # 更新配置
        self.config["mail_addr"] = current_text

        # 自动取消自动连接选项
        self.auto_connect_var.set(False)
        self.config["auto_connect"] = False
        self.frpc.set_mail(self.config["mail_addr"])
        self.write_config(self.config)

    def on_auto_connect_toggle(self):
        """当自动连接选项切换时触发"""
        is_checked = self.auto_connect_var.get()
        print(f"自动连接选中状态: {'选中' if is_checked else '未选中'}")
        if is_checked:
            self.start_frpc()
        else:
            self.frpc.stop()

        # 更新配置
        self.config["auto_connect"] = is_checked
        self.write_config(self.config)
        if self.hide_timer:
            self.root.after_cancel(self.hide_timer)

    def hide_window(self):
        """隐藏窗口"""
        self.root.withdraw()
        print("窗口已隐藏：一分钟无输入活动")

    def validate_hotkey(self, hotkey):
        """验证热键格式"""
        if not hotkey:
            return False
        valid_keys = ['Ctrl', 'Alt', 'Shift'] + [chr(i) for i in range(65, 91)]  # A-Z
        keys = hotkey.split('+')
        return all(key in valid_keys for key in keys)

    def update_hotkey(self):
        """更新热键"""
        custom_hotkey = self.custom_hotkey_entry.get()
        if self.validate_hotkey(custom_hotkey) and self.config["hot_key"] != custom_hotkey:
            self.current_hotkey = custom_hotkey
            self.register_hotkey()
            self.config["hot_key"] = custom_hotkey
            self.write_config(self.config)
            print(f"热键已更新为: {custom_hotkey}")
        else:
            print("无效的热键格式！请使用类似 'Ctrl+Alt+T' 的格式。")

    def register_hotkey(self):
        """注册热键"""
        if self.current_hotkey:
            self.unregister_hotkey()

        try:
            keyboard.add_hotkey(self.current_hotkey, self.toggle_window)
            print(f"热键已注册: {self.current_hotkey}")
        except Exception as e:
            print(f"无法注册热键 {self.current_hotkey}: {e}")

    def unregister_hotkey(self):
        """注销热键"""
        try:
            keyboard.remove_hotkey(self.current_hotkey)
            print(f"热键已注销: {self.current_hotkey}")
        except KeyError:
            print(f"热键未注册: {self.current_hotkey}")

    def toggle_window(self):
        """切换窗口显示/隐藏"""
        if self.root.state() == 'normal':
            self.root.withdraw()
        else:
            self.root.deiconify()

    def update_output_label(self, ip, port):
        """更新 output_label 的显示内容"""
        self.output_label.config(text=f"IP: {ip}\n端口: {port}")


if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()
